<template>
  <div>
    <Card>
      <div  class="search-con search-con-top">
        <Button style="margin-right: 10px;" type="primary" @click="addOrUpdate = true">添加</Button>
        <Button style="margin-right: 10px;" type="primary" @click="exportExcel">导出为Csv文件</Button>
        <Select v-model="searchKey" class="search-col" placeholder="请选择检索项">
          <Option v-for="item in columns" v-if="item.key !== 'handle'" :value="item.key" :key="item.key">{{ item.title }}</Option>
        </Select>
        <Input clearable placeholder="输入关键字搜索" class="search-input" v-model="searchValue"/>
        <Button @click="handleSearch" class="search-btn" type="primary"><Icon type="search"/>&nbsp;&nbsp;搜索</Button>
      </div>
      
      <tables :height="innerHeight - 250" ref="tables" search-place="top" v-model="tableData" :columns="columns" :loading="tabLoading"/>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
            <Page :total="total" size="small" show-elevator show-sizer @on-change="changePage" @on-page-size-change="pageSizeChange"/>
        </div>
      </div>
    </Card>
    <Modal v-model="addOrUpdate" :title="modelTitle" @on-ok="ok" @on-cancel="cancel" :mask-closable="false" width="700">
        <Form ref="addFrom" :model="addFrom" :label-width="100">
            <Row>
                <Col span="12">
                    <FormItem label="优惠名称" prop="couponName" :rules="{required: true, message: '请填写优惠名称', trigger: 'blur'}">
                        <Input v-model="addFrom.couponName" placeholder="请填写优惠名称"></Input>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="优惠方式" prop="couponFunc" :rules="{required: true, message: '请填写优惠方式', trigger: 'blur'}">
                        <Input v-model="addFrom.couponFunc" placeholder="填写优惠方式"></Input>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="优惠描述" prop="couponDesc" :rules="{required: true, message: '请填写优惠描述', trigger: 'blur'}">
                        <Input v-model="addFrom.couponDesc" placeholder="填写优惠描述"></Input>
                    </FormItem>
                </Col>
                
                <Col span="12">
                    <FormItem label="优惠金额" prop="couponDecimal" :rules="{required: true, message: '请填写优惠金额', trigger: 'blur'}">
                        <Input v-model="addFrom.couponDecimal" placeholder="填写优惠金额"></Input>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="所属机构" prop="relId" :rules="{required: true, message: '请选择所属机构', trigger: 'blur'}">
                        <Select
                            v-model="addFrom.relId"
                            filterable
                            remote
                            :remote-method="remotePrv"
                            :loading="prvloading">
                            <Option v-for="(option, index) in prvs" :value="option.prvId" :key="index">{{option.prvName}}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="最大派发数量" prop="maxReleaseNumber" :rules="{required: true, message: '请填写最大派发数量', trigger: 'blur'}">
                        <Input v-model="addFrom.maxReleaseNumber" placeholder="填写最大派发数量"></Input>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="可领取最大数量" prop="getMaxNumber" :rules="{required: true, message: '请填写可领取最大数量', trigger: 'blur'}">
                        <Input v-model="addFrom.getMaxNumber" placeholder="填写可领取最大数量"></Input>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="起效开始日期" prop="effeDateFrom">
                        <DatePicker type="date" placeholder="选择起效开始日期" v-model="addFrom.effeDateFrom" @on-change="effeDateFromchange"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="起效截至日期" prop="effeDateEnd">
                        <DatePicker type="date" placeholder="选择起效截至日期" v-model="addFrom.effeDateEnd" @on-change="effeDateEndchange"></DatePicker>
                    </FormItem>
                </Col>
            </Row>
        </Form>
    </Modal>
  </div>
</template>

<script>
//Provider 机构级别  Product课程  Topic 咨讯
import Tables from '_c/tables'
import { tablePublicRequest } from '@/api/data'
export default {
  name: 'tables_page',
  components: {
    Tables
  },
  data () {
    return {
      actionUrl:{
        "BATCH":"smc/buy/CouponVoucher/saveCouponVoucher.json",
  		  "QRY": "smc/buy/CouponVoucher/queryCouponVoucher.json",
  		  "ADD":"smc/buy/CouponVoucher/addCouponVoucher.do",
  		  "DEL":"smc/buy/CouponVoucher/delCouponVoucher.do",
  		  "UPD":"smc/buy/CouponVoucher/updCouponVoucher.do",
  		  "LKUP":"smc/buy/CouponVoucher/lookupCouponVoucher.json",
  		  "LST":"smc/buy/CouponVoucher/listCouponVoucher.json",
        "FIND":"smc/buy/CouponVoucher/findCouponVoucher.json",
        "PRVLST":"smc/base/SystemProviderUser/listSystemProviderUser.json"
      },    
      innerHeight:document.body.clientHeight,
      addOrUpdate: false,
      modelTitle:"新增",
      searchKey:"",
      searchValue:"",
      page:1,
      pageSize:10,
      total:0,
      search:{},
      prvloading:false,
      prvs:[],
      tabLoading:true,
      addFrom:{
        relType:'Provider'
      },
      columns: [
        {title: '优惠名称', key: 'couponName', editable: true},
        {title: '优惠方式', key: 'couponFunc', sortable: true},
        {title: '优惠描述', key: 'couponDesc', sortable: true},
        {title: '优惠金额', key: 'couponDecimal', sortable: true},
        {title: '所属机构', key: 'relIdName', sortable: true},
        {title: '最大派发数量', key: 'maxReleaseNumber', sortable: true},
        {title: '已派发数量', key: 'releasedNumber', sortable: true},
        {title: '可领取最大数量', key: 'getMaxNumber', sortable: true},
        {title: '起效开始日期', key: 'effeDateFrom', sortable: true},
        {title: '起效截至日期', key: 'effeDateEnd', sortable: true},
        {
          title: '操作',
          key: 'handle',
          fixed:'left',
          width:80,
          button: [
            (h, params, vm) => {
              return h('Button', {
                  props: {
                    type: 'text',
                    ghost: true
                  },
                  attrs:{
                    style:"padding: 5px 0;"
                  },
                  on: {
                    'click': () => {
                      tablePublicRequest(this.actionUrl.FIND,{"id":params.row.couponId}).then(res => {
                        let data = res.data;
                        if(data.success){
                          var da = data.data;
                          da.effeDateFrom = this.getDate(da.effeDateFrom);
                          da.effeDateEnd = this.getDate(da.effeDateEnd);
                          this.addFrom = da || {};
                          this.addOrUpdate = true;
                        }
                      })
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'ios-create',
                      size: 18,
                      color: '#000000'
                    }
                  })
              ])
            },
            (h, params, vm) => {
              return h('Poptip', {
                props: {
                  confirm: true,
                  title: '你确定要删除吗?',
                  transfer:true
                },
                on: {
                  'on-ok': () => {
                    tablePublicRequest(this.actionUrl.DEL,{"id":params.row.couponId}).then(res => {
                      let data = res.data;
                      if(data.success){
                        this.$Message.info('删除成功！');
                        this.handleSearch();
                      }
                    })
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'text',
                    ghost: true
                  },
                  attrs:{
                    style:"padding: 5px 0;"
                  },
                }, [
                  h('Icon', {
                    props: {
                      type: 'md-trash',
                      size: 18,
                      color: '#000000'
                    }
                  })
                ])
              ])
            }
          ]
        }
      ],
      tableData: []
    }
  },
  methods: {
    effeDateFromchange(value){
this.addFrom.effeDateFrom = value;
    },
    effeDateEndchange(value){
this.addFrom.effeDateEnd = value;
    },
    remotePrv(query){
      if (query !== '') {
          this.prvloading = true;
          tablePublicRequest(this.actionUrl.PRVLST,{"$prvName-contains":query}).then(res => {
            let data = res.data;
            if(data.success){
              this.prvloading = false;
              this.prvs = data.data;
            }
          })
      } else {
          this.prvs = [];
      }
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    ok () {
      delete this.addFrom.createdAt;
      delete this.addFrom.lastedUpdAt;
      let url = this.addFrom.couponId?this.actionUrl.UPD:this.actionUrl.ADD;
      this.modelTitle = this.addFrom.couponId?"修改":"新增";
      
      tablePublicRequest(url,this.addFrom).then(res => {
        let data = res.data;
        if(data.success){
          this.$Message.info(`${this.modelTitle}成功！`);
          this.handleSearch();
          this.addFrom = {relType:'Provider'};
        }
      })
    },
    cancel () {
        this.addFrom = {relType:'Provider'};
    },
    changePage (data) {
      this.page = data;
      this.handleSearch();
    },
    pageSizeChange(data){
      this.pageSize = data;
      this.handleSearch();
    },
    handleSearch(){
      this.search = {page: this.page,pagesize: this.pageSize};
      this.search.searchRules=`[{"op":"contains","field":"${this.searchKey}","value":"${this.searchValue}","type":"text"}]`;
      this.setTableData(this.search);
    },
    setTableData(params){
      this.tabLoading = true;
      tablePublicRequest(this.actionUrl.QRY,params).then(res => {
        let data = res.data;
        if(data.success){
          let tdata = data.data;
          this.total = tdata.total;
          let rws = tdata.rows||[];
          for(var i=0;i<rws.length;i++){
            rws[i].effeDateFrom = this.getDate(rws[i].effeDateFrom);
            rws[i].effeDateEnd = this.getDate(rws[i].effeDateEnd);
          }
          this.tabLoading = false;
          this.tableData = tdata.rows||[];
        }
      })
    },
    handleSuccess(res, file){
      this.$Message.info(res.msg);
      this.addFrom.prodMainImg = res.path;
    },
    handleError(res, file){
      this.$Message.info(res.msg);
    },
    // 格式化时间戳
    getDate(timestamp) {
      var time = arguments[0] || 0;
      var t, y, m, d, h, i, s;
      t = time ? new Date(time) : new Date();
      y = t.getFullYear();    // 年
      m = t.getMonth() + 1;   // 月
      d = t.getDate();        // 日
      h = t.getHours();       // 时
      i = t.getMinutes();     // 分
      s = t.getSeconds();     // 秒

      // 定义时间格式
      return y
        + '-'
        + (m < 10 ? '0' + m : m)
        + '-'
        + (d < 10 ? '0' + d : d)
    }
  },
  mounted () {
    this.setTableData({page: this.page,pagesize: this.pageSize});
  }
}
</script>

<style>

</style>
